package com.iflyun.LogsCustmerToHDFS.listener;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.iflyun.LogsCustmerToHDFS.entity.CallLog;
import com.iflyun.LogsCustmerToHDFS.service.ApiLogService;





/**
 * 
 * @ClassName:  ApiLogListener   
 * @Description:api接口日志队列监听器   
 * @author: wenquxing  
 * @date:   2017年8月25日 下午1:13:30   
 *
 */
public class ApiLogListener implements  MessageListener {
	
	private static final Logger logger = LoggerFactory.getLogger(ApiLogListener.class);
	
	private static List<CallLog> list =new ArrayList<CallLog>();
	
	private static String fileName="";
	
	private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	
	
	@Autowired
	private ApiLogService apiLogService;
	
	
	@Override
	public void onMessage(Message message) { 
		String json="";
		CallLog apilog=null;
		Date date=null;
		Date date1=null;
		Date date2=null;
		String tsStr="";
		try {
			json=new String(message.getBody(), "UTF-8");
			apilog = JSON.parseObject(json, CallLog.class);
			//为空则赋值为当前时间
			if("".equals(fileName)) {
				date=new Date(); 
				fileName=sdf.format(date);
			}else {
				try {
					tsStr = sdf.format(apilog.getCreatTime());		
					date1 = sdf.parse(tsStr); //数据时间
					date2=sdf.parse(fileName);//当前目录时间
				} catch (ParseException e) {
					e.printStackTrace();
				}
//				数据时间大于当前文件时间
				if(date1.getTime()>date2.getTime()) {
					list=apiLogService.setApiLogList(list,fileName);//入hdfs
					fileName=tsStr;	//将数据时间赋予文件时间	
					list.add(apilog);
				}else if(date1.getTime()<date2.getTime()) {
					logger.error("数据时间小于当前目录时间:"+apilog.getId());
				}else {
					list.add(apilog);
				}
										
			}		
			
		} catch (UnsupportedEncodingException e) {
			logger.error("json转换失败:",e);
		}
		
		if(list.size()>=1000){
			list=apiLogService.setApiLogList(list,fileName);
		}
	
    }

}